package org.administer.contaroller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sun.tracing.dtrace.ArgsAttributes;
import org.administer.dao.CrmPermissionDao;
import org.administer.dao.CrmRoleDao;
import org.administer.dao.CrmUserDao;
import org.administer.pojo.CrmPermission;
import org.administer.pojo.CrmRole;
import org.administer.pojo.CrmUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/User")
public class UserController {

    @Autowired
    private CrmUserDao userDao;
    @Autowired
    private CrmPermissionDao crmPermissionDao;
    @Autowired
    private CrmRoleDao crmRoleDao;

    @GetMapping("/login")
    public String login() throws Exception{
        return "login";
    }

    @RequestMapping("/success")
    @ResponseBody
    public  Map<String,Object> success(HttpSession session) throws Exception {
//        System.out.println("success");
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);

        //存储登录的用户
        CrmUser crmUser=(CrmUser) SecurityUtils.getSubject().getPrincipal();
        session.setAttribute("login_user",crmUser);
        System.out.println("用户编号"+crmUser.getId());
//        CrmUser roleid=userDao.get(crmUser.getId());
//        session.setAttribute("crmRole",roleid);
//        System.out.println("职位"+roleid.getCrmRole().getRolename());

        //存储登录用户id，负责显示相对应的权限信息
        List<CrmPermission> perlist = crmPermissionDao.getPersByUserId(crmUser.getId());
        session.setAttribute("user_pers",perlist);
        return map;
    }

    /**
     * post方式的login方式什么时候调用？
     * 身份认证失败的时候会自动调用
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request) throws Exception{
        Map<String,Object> map = new HashMap<>();
//        System.out.println("认证失败了吧！来我这了吧");
        String exceptionName = request.getAttribute("shiroLoginFailure").toString();
        if (exceptionName.equals(UnknownAccountException.class.getName())){     //用户名不正确
            map.put("code",1);
            map.put("msg","用户名不正确");
            return map;
        }else if(exceptionName.equals(IncorrectCredentialsException.class.getName())){      //密码不正确
            map.put("code",2);
            map.put("msg","密码不正确");
            return map;
        }else if(exceptionName.equals(LockedAccountException.class.getName())){        //是否锁定
            map.put("code",3);
            map.put("msg","该账户已被锁定...");
            return map;
        }
        return null;
    }
    @GetMapping("/main")
    public String main() throws Exception{
        return "main";
    }
    @RequestMapping("/index")
    public String index() throws Exception{
        return "/user/userindex";
    }

    @RequestMapping("/infoindex")
    public String info() throws Exception{
        return "user/info";
    }

    @RequestMapping("/info")
    @ResponseBody
    public CrmUser info(CrmUser crmUser) throws Exception{
        CrmUser user=(CrmUser) SecurityUtils.getSubject().getPrincipal();
        return userDao.get(user.getId());
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String,Object> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit, CrmUser condition) throws Exception{
        Map<String,Object> map=new HashMap<>();
        Page<CrmUser> pager= PageHelper.startPage(page,limit);
        List<CrmUser> list=userDao.getlist(condition);
        map.put("code",0);
        map.put("msg",null);
        map.put("data",list);
        map.put("count",pager.getTotal());

        return map;
    }

    @RequestMapping("/search")
    @ResponseBody
    public List<CrmRole> search() throws Exception{
        return crmRoleDao.getAll();
    }

    @RequestMapping("/addform")
    public String form(ModelMap modelMap) throws Exception{
        modelMap.put("roleList",crmRoleDao.getAll());
        return "user/addform";
    }



    @RequestMapping(value = "/add",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> add(CrmUser crmUser,Integer roleIds) throws Exception{
        Map<String,Object> map=new HashMap<>();
        //进行盐值与密码的结合来加密
        Md5Hash md5Hash=new Md5Hash(crmUser.getPassword(),crmUser.getSalt());
        crmUser.setPassword(md5Hash.toString());
        userDao.add(crmUser);
        userDao.addUserRole(crmUser.getId(),roleIds);
        map.put("result",true);
        return map;
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    public Map<String,Object> batchDelete(Integer[] ids) throws Exception{
        Map<String,Object> map=new HashMap<>();
        userDao.delete(ids);
        map.put("result",true);
        return map;
    }

    @RequestMapping("/view")
    @ResponseBody
    public CrmUser view(Integer id) throws Exception{
        return userDao.get(id);
    }


    @RequestMapping("/updateform")
    public String form1(HttpSession session) throws Exception{
        List<CrmRole> crmRoleList= crmRoleDao.getAll();
        session.setAttribute("crmRoleList",crmRoleList);
        return "/user/updateform";
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> update(CrmUser crmUser, Integer roleIds, MultipartFile picture, HttpServletRequest request) throws Exception{
        Map<String,Object> map=new HashMap<>();
        userDao.update(crmUser);
        userDao.deleteUserRole(crmUser.getId());
        userDao.addUserRole(crmUser.getId(),roleIds);
//        //获取未修改的用户信息
//        CrmUser psUser1 = userDao.get(crmUser.getId());
//        //不修改密码和盐值
//        if(!crmUser.getPassword().equals(psUser1.getPassword())) {
//            //进行密码加密
//            Md5Hash md5Hash = new Md5Hash(crmUser.getPassword(), crmUser.getSalt());
//            crmUser.setPassword(md5Hash.toString());
//        }

        map.put("result",true);
        return map;

    }
    @RequestMapping(value = "/updateuser",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateuser(CrmUser crmUser, Integer roleIds, MultipartFile picture, HttpServletRequest request) throws Exception{
        Map<String,Object> map=new HashMap<>();
        userDao.updatauser(crmUser);
//        //获取未修改的用户信息
//        CrmUser psUser1 = userDao.get(crmUser.getId());
//        //不修改密码和盐值
//        if(!crmUser.getPassword().equals(psUser1.getPassword())) {
//            //进行密码加密
//            Md5Hash md5Hash = new Md5Hash(crmUser.getPassword(), crmUser.getSalt());
//            crmUser.setPassword(md5Hash.toString());
//        }

        map.put("result",true);
        return map;

    }
}
